<template>
  <div class="app-container">
    <el-form
      :model="formData"
      label-width="100px"
      label-position="top"
      status-icon
      align="center"
    >
      <el-form-item label="" prop="url">
        <!-- 上传图片 -->
        <el-upload
          class="avatar-uploader"
          action=""
          accept="image/*"
          :show-file-list="false"
          :http-request="uploadImg"
          :before-upload="beforeUpload"
        >
          <!-- 如果有图片，显示图片 -->
          <img v-if="formData.url" :src="formData.url" class="avatar" alt="">
          <!-- 如果没有图片，显示那个 + 号，底下的样式就是 + 号 加边框 -->
          <i v-else class="el-icon-plus avatar-uploader-icon"/>
        </el-upload>
      </el-form-item>
      <div style="margin-top: 50px;">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-form>
  </div>
</template>
<script>
import api from '@/api/background'

export default {
  name: 'BackgroundAdd',
  props: ['formData'],
  methods: {
    // 上传图片之前的钩子（限制上传图片大小）
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isLt2M
    },
    // 上传图片
    uploadImg(file) {
      const data = new FormData()
      data.append('file', file.file)
      // background 为指定上传后的目录名
      api.uploadImg('background', data).then(response => {
        if (response.code === 200) {
          // 以防图片多次上传，上传成功后，把原来的图片删除
          this.removeImg()
          this.formData.url = response.data.fileUrl
          this.$message.success('上传图片成功')
        } else {
          this.$message.error(response.message)
        }
      }).catch(() => {
        this.$message.error('上传失败')
      })
    },
    // 删除之前上传无用的图片
    removeImg() {
      if (this.formData.url) {
        api.deleteImg(this.formData.url)
      }
    },
    // 取消-删除上传的图片
    cancel() {
      this.removeImg()
      this.$emit('handleClose')
    },
    // 提交表单
    async submitForm() {
      // 提交数据给后台
      api.add(this.formData).then(response => {
        if (response.code === 200) {
          // 刷新数据列表
          this.$emit('fetchData')
          this.$emit('handleClose')
          this.$message.success('新增背景图片成功')
        } else {
          this.$message.error(response.message)
        }
      })
    }
  }
}
</script>
<style>
.el-dialog__body {
  padding: 0 20px;
}
/* 上传图片 */
.avatar-uploader .el-upload {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  background: #fdfdfd;
}

.avatar-uploader .el-upload:hover {
  border-color: #000000;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  height: 310px;
  width: 100%;
  min-width: 500px;
  line-height: 280px;
  text-align: center;
}

.avatar {
  height: 310px;
  width: 100%;
  min-width: 500px;
  display: block;
}
</style>
